<?php

namespace App\Models\House;

use App\Models\Base;
use App\Models\Common\CommonParam;
use App\Models\User\SystemUser;
use Illuminate\Database\Eloquent\SoftDeletes;

class House extends Base
{
    use SoftDeletes;
    protected $table = 'houses';

    protected $casts = [
        'price' => 'float',
        'size' => 'int',
        'selltype' => 'int',
        'area' => 'json',
        'status' => 'int',
        'user_id' => 'int'
    ];

    protected $fillable = [
        'price',
        'price_unit',
        'remark',
        'village',
        'size',
        'selltype',
        'total_floors',
        'detail_address',
        'area',
        'internal_structure',
        'landlord_id',
        'status',
        'user_id'
    ];
    //
    const STATUS = [
        '',
        '未租售',
        '已租售'
    ];
    const  STATUS_UNSOLD = 1; // 未卖
    const  STATUS_SOLD = 2; // 已卖


    public function HouseImg()
    {
        return $this->hasMany(HouseImg::class,'house_id');
    }
    public function imges()
    {
        return $this->hasMany(HouseImg::class,'house_id');
    }

    public function User()
    {
        return $this->belongsTo(SystemUser::class,'user_id','id');
    }

    # 房屋根据记录
    public function FllowupRecord()
    {
        return $this->hasMany(HouseFllowupRecord::class,'house_id');
    }


    ##  获取 房屋【属性-值】
    public function getHouseAttrValue($house_id)
    {
        $attr =  $this->getAllAttr();
        ## 值；

    }
    # 获取所有的属性
    public function getAllAttr()
    {
        $attr = cache('getAllAttr');
        if ($attr) {
            return $attr;
        }
        $houseAttrParamIds = HouseAttribute::query()
            ->where('house_type','house_sell')
            ->get()->pluck('param_id');
        $data = CommonParam::query()->whereIn('id', $houseAttrParamIds)->get();
        cache()->put('getAllAttr', $data);
        return $data;
    }

    # 房屋 属性值；
    public function getValues($house_id)
    {
        $attr = $this->getAllAttr();
        $paramsIds = $attr->pluck('id');

        $data = CommonParam::query()
            ->whereHas(
            'HouseAttrone',function($query)use($house_id){
                return $query->where('house_id',$house_id);
            })
            ->whereIn('id', $paramsIds)
            ->with(
                [
                'childParam' => function($query){
                    $query->select(['id','parent_id','name']);
                },
            'HouseAttrone' =>function($query)use($house_id){
                   return  $query->where('house_id', $house_id);
                },
            ])
            ->select([
                'id','parent_id','name','field'
            ])
            ->get()
           ->toArray();
//            dd($house_id, $data);
          return $data;


    }

    # 房东信息
    public function landlord()
    {
        return $this->belongsTo(Landlord::class,'landlord_id','id');
    }



}
